package com.yanqu.road.server.cmd.monopolymarket;

import com.yanqu.road.entity.enums.eMonopolyMarketResType;
import com.yanqu.road.entity.monopolymarket.group.MonopolyMarketServerGroup;
import com.yanqu.road.logic.bussiness.monopolymarket.MonopolyMarketBussiness;
import com.yanqu.road.pb.monopolymarket.MonopolyMarketProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.monopolymarket.MonopolyMarketModule;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.MonopolyMarketCommonMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.monopolymarket.MonopolyMarketMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.BitUtil;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;

/**
 * @Description
 * @Author cwq
 * @Data 2021/8/20 10:25
 */
@Cmd(code = GameProtocol.S_MONOPOLY_MARKET_SYN_CROSS_GROUP, desc = "跨服 下发榷场的分组配置")
public class MonopolyMarketSynCrossGroupFromCrossCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
        MonopolyMarketProto.MonopolyMarketSynCrossGroupToGameServerMsg resp = MonopolyMarketProto.MonopolyMarketSynCrossGroupToGameServerMsg.parseFrom(packet.getBytes());
        if(!resp.hasCrossGroup()){
            MonopolyMarketMgr.logger.error("跨服 下发榷场的分组配置 数据异常！！ 没有分组配置");
            return;
        }
        MonopolyMarketMgr.logger.info("收到跨服下发的榷场分组数据！！分组id:{},区服:{},state:{}.fortressState:{}",resp.getCrossGroup().getGroupId(),resp.getCrossGroup().getServerListList(),resp.getCrossGroup().getState(),resp.getCrossGroup().getFortressState());
        synchronized (MonopolyMarketSynCrossGroupFromCrossCmd.class){
            new ConfigMgr().reloadConfig();
            new MonopolyMarketMgr().reloadConfig();
            if(MonopolyMarketMgr.group == null){
                int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
                // 服务启动 请求跨服获得的分组信息
                MonopolyMarketServerGroup group = new MonopolyMarketServerGroup();
                group.setInsertOption();
                group.setServerId(GameServer.getInstance().getServerId());
                group.setChannelId(channelId);
                group.setGroupId(resp.getCrossGroup().getGroupId());
                group.setServerList(resp.getCrossGroup().getServerListList());
                group.setState(resp.getCrossGroup().getState());
                group.setFortressState(resp.getCrossGroup().getFortressState());
                group.setChangTime(resp.getCrossGroup().getChangTime());
                group.setOfficeCfgChangTime(resp.getCrossGroup().getOfficeCfgChangTime());
                group.setKingCfgChangTime(resp.getCrossGroup().getKingCfgChangTime());
                group.setQueenCfgChangTime(resp.getCrossGroup().getQueenCfgChangTime());
                MonopolyMarketMgr.group = group;
                MonopolyMarketMgr.initMap();

                List<GamePlayer> playerList = GamePlayerMgr.getAllOnlinePlayer();
                for(GamePlayer item : playerList){
                    MonopolyMarketModule marketModule = item.getModule(MonopolyMarketModule.class);
                    marketModule.initModule();
                }
            }else {
                // 校验分组变化
                int changeBit = checkMonopolyMarketServerGroup(MonopolyMarketMgr.group,resp.getCrossGroup());
                if(changeBit > 0 ){
                    MonopolyMarketMgr.logger.info("榷场分组发生变化，重置数据。bit:{}",changeBit);
                    MonopolyMarketMgr.resetUserData(changeBit, true);
                    if(BitUtil.get(changeBit, eMonopolyMarketResType.OFFICE.getValue() - 1)){

                    }
                    if(BitUtil.get(changeBit,eMonopolyMarketResType.RES_KING.getValue() - 1)){
                        MonopolyMarketMgr.initMap(eMonopolyMarketResType.RES_KING.getValue());
                    }
                    if(BitUtil.get(changeBit,eMonopolyMarketResType.RES_QUEEN.getValue() - 1)){
                        MonopolyMarketMgr.initMap(eMonopolyMarketResType.RES_QUEEN.getValue());
                    }
                    List<GamePlayer> playerList = GamePlayerMgr.getAllOnlinePlayer();
                    for(GamePlayer item : playerList){
                        item.getModule(MonopolyMarketModule.class).sendConfigToClient();
                    }
                }
            }
            MonopolyMarketMgr.isSyn = true;
        }
    }

    /**
     * 检查分组是否发生改变
     * @param serverGroup
     * @param crossGroupEntity
     * @return
     */
    public int checkMonopolyMarketServerGroup(MonopolyMarketServerGroup serverGroup,MonopolyMarketProto.MonopolyMarketCrossGroupEntity crossGroupEntity){
        MonopolyMarketMgr.logger.info("serverGroup！！分组id:{},channelId:{},changeTime:{},区服:{},state:{},fortressState:{},officeCfgChangTime：{},kingCfgChangTime：{},queenCfgChangTime：{}.",serverGroup.getGroupId(),serverGroup.getChannelId(),serverGroup.getChangTime(),serverGroup.getServerList(),serverGroup.getState(),serverGroup.getFortressState(),serverGroup.getOfficeCfgChangTime(),serverGroup.getKingCfgChangTime(),serverGroup.getQueenCfgChangTime());
        MonopolyMarketMgr.logger.info("crossGroupEntity！！分组id:{},channelId:{},changeTime:{},区服:{},state:{}.fortressState:{},officeCfgChangTime：{},kingCfgChangTime：{},queenCfgChangTime：{}.",crossGroupEntity.getGroupId(),crossGroupEntity.getChannelId(),crossGroupEntity.getChangTime(),crossGroupEntity.getServerListList(),crossGroupEntity.getState(),serverGroup.getFortressState(),crossGroupEntity.getOfficeCfgChangTime(),crossGroupEntity.getKingCfgChangTime(),crossGroupEntity.getQueenCfgChangTime());
        int bit = 0;
        if(serverGroup.getGroupId() != crossGroupEntity.getGroupId()){
            bit = MonopolyMarketCommonMgr.SYSTEM_BIT;
        }else if(serverGroup.getChannelId() != crossGroupEntity.getChannelId()){
            bit = MonopolyMarketCommonMgr.SYSTEM_BIT;
        }else if(serverGroup.getChangTime() != crossGroupEntity.getChangTime()){
            bit = MonopolyMarketCommonMgr.SYSTEM_BIT;
        }else if(serverGroup.getServerList().size() != crossGroupEntity.getServerListCount()){
            bit = MonopolyMarketCommonMgr.SYSTEM_BIT;
        }else if(serverGroup.getState() != crossGroupEntity.getState()){
            bit = MonopolyMarketCommonMgr.SYSTEM_BIT;
        } else if (serverGroup.getFortressState() != crossGroupEntity.getFortressState()) {
            bit = BitUtil.set(bit,eMonopolyMarketResType.FORTRESS.getValue()-1,true);
        } else {
            for (long serverId : serverGroup.getServerList()) {
                if (!crossGroupEntity.getServerListList().contains(serverId)) {
                    bit = MonopolyMarketCommonMgr.SYSTEM_BIT;
                }
            }
            for (long serverId : crossGroupEntity.getServerListList()) {
                if (!serverGroup.getServerList().contains(serverId)) {
                    bit = MonopolyMarketCommonMgr.SYSTEM_BIT;
                }
            }
        }
        boolean cfgChange = false;
        if(serverGroup.getOfficeCfgChangTime() != crossGroupEntity.getOfficeCfgChangTime()){
            bit = BitUtil.set(bit,0,true);
            cfgChange = true;
        }
        if(serverGroup.getKingCfgChangTime() != crossGroupEntity.getKingCfgChangTime()){
            bit = BitUtil.set(bit,1,true);
            cfgChange = true;
        }
        if(serverGroup.getQueenCfgChangTime() != crossGroupEntity.getQueenCfgChangTime()){
            bit = BitUtil.set(bit,2,true);
            cfgChange = true;
        }
        if(bit > 0){
            serverGroup.setGroupId(crossGroupEntity.getGroupId());
            serverGroup.setChannelId(crossGroupEntity.getChannelId());
            serverGroup.setServerList(crossGroupEntity.getServerListList());
            serverGroup.setChangTime(crossGroupEntity.getChangTime());
            serverGroup.setState(crossGroupEntity.getState());
            serverGroup.setFortressState(crossGroupEntity.getFortressState());
            serverGroup.setOfficeCfgChangTime(crossGroupEntity.getOfficeCfgChangTime());
            serverGroup.setKingCfgChangTime(crossGroupEntity.getKingCfgChangTime());
            serverGroup.setQueenCfgChangTime(crossGroupEntity.getQueenCfgChangTime());
        }
        if(cfgChange){
            int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
            MonopolyMarketMgr.backEndConfig = MonopolyMarketBussiness.getMonopolyMarketBackEndConfig(channelId);
        }
        return bit;
    }

}
